<?php
namespace Common;
/**
 * Class CommonController 工具类
 */
class CommonAd
{
    const EXCLUSIVECODE_MONEY = 0.01;


    const TAOBAO = 'haodanku';//taobao
    const JD = 'jd';
    const PINDUODUO = 'pdd';//pinduoduo

    const PAGESIZE = 10;
    const PAGE = 1;

    const ORDER_STATUS = array(
        1  => '待支付',
        2  => '待发货',
        3  => '已退款',
        4  => '待收货',
        5  => '已失效',
        6  => '已结算',
        11 => '已取消',
    );
    const LEVEL_NAME = [
        1 => '合伙人',
        2 => '团队长',
        3 => '高级团队长',
    ];
    const JD_APP = array(
        'KEY'    => '79ab36193d1acde1c7361d07c6e124b6',
        'SECRET' => '1167f168d96b48d1a21911361b78adc2',
        'METHOD' => 'jd.union.open.promotion.bysubunionid.get',
    );

    const TAOBAO_APP = array(
        'CLIENT_ID' => '25284833',
        'SECRET'    => '5a63a40cbcf14e45fe6f23dd8cd1bf69',
    );

    const INVITECODELENGTH = 6;

    //静态资源域名
    public static $RESOURCE_URL = [
        'qiniu' => 'http://jzcloud.jiruan.ltd/'
    ];

    /**
     * @func 返回一个六位数的随机数
     * @return int
     */
    public static function getInviteCode()
    {
        return rand(100000, 999999);
    }


    /**
     * @func 获取一个时间节点
     * @param $time_type 1 今日 2 昨日 3 近七天 4 15天 5 30天 6 60天 7 90天 8 本月 9 上月 10前天 11近三天 12半年 13今年 14本周 15上周
     * @return array
     */
    public static function timeChange($time_type)
    {
        switch ($time_type) {
            case 1:
                //获取今日开始时间戳和结束时间戳
                $start = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $end   = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                break;
            case 2:
                //获取昨日开始时间戳和结束时间戳
                $start = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
                $end   = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
                break;
            case 3:
                //获取七天开始时间戳和结束时间戳
                $start = mktime(0, 0, 0, date('m'), date('d') - 6, date('Y'));
                $end   = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
                break;
            case 4:
                //获取15天
                $start = mktime(0, 0, 0, date('m'), date('d') - 14, date('Y'));
                $end   = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
                break;
            case 5:
                //获取30天
                $start = mktime(0, 0, 0, date('m'), date('d') - 29, date('Y'));
                $end   = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
                break;
            case 6:
                //获取60天
                $start = mktime(0, 0, 0, date('m'), date('d') - 59, date('Y'));
                $end   = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
                break;
            case 7:
                //获取90天
                $start = mktime(0, 0, 0, date('m'), date('d') - 89, date('Y'));
                $end   = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
                break;
            case 8:
                //获取本月
                $start = mktime(0, 0, 0, date('m'), 1, date('Y'));
                $end   = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
                break;
            case 9:
                //获取上月
                $start = mktime(0, 0, 0, date('m') - 1, 1, date('Y'));
                $end   = mktime(23, 59, 59, date('m'), 1 - 1, date('Y'));
                break;
            case 10:
                //获取前天开始时间戳和结束时间戳
                $start = mktime(0, 0, 0, date('m'), date('d') - 2, date('Y'));
                $end   = $start + 86399;
                break;
            case 11:
                //获取三天开始时间戳和结束时间戳
                $start = mktime(0, 0, 0, date('m'), date('d') - 2, date('Y'));
                $end   = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
                break;
            case 12:
                //获取半年开始时间戳和结束时间戳
                $start = mktime(0, 0, 0, date('m'), date('d') - 179, date('Y'));
                $end   = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
                break;
            case 13:
                //获取一年开始时间戳和结束时间戳
                $start = strtotime(date('Y-') . "01-01 00:00:00");
                $end   = strtotime(date('Y-') . "12-31 23:59:59");
                break;
            case 14:
                //获取本周的时间
                $start = strtotime(date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y"))));
                $end   = strtotime(date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y"))));
                break;
            case 15:
                $start = strtotime(date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1 - 7, date("Y"))));
                $end = strtotime(date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7 - 7, date("Y"))));
                break;
        }
        $times = array('start_at' => date("Y-m-d H:i:s", $start), 'end_at' => date("Y-m-d H:i:s", $end));
        return $times;
    }


    /**
     * @param $tb_rid  淘宝授权码
     * @param $goods_id 商品id
     * @return array
     */
    public static function taobao_turn($tb_rid, $goods_id)
    {
        $request_url  = 'http://v2.api.haodanku.com/ratesurl';
        $request_data = [
            'apikey'      => 'ousheng',
            'itemid'      => (int)$goods_id,
            'pid'         => 'mm_1279570013_1941750243_110811150439',
            'relation_id' => $tb_rid,
            'tb_name'     => '云聚商'
        ];
        $res          = self::request_post($request_url, $request_data);
        if ($res['code'] != 1) {
            return ['status' => false, 'msg' => $res['msg']];
        } else {
            if ($res['data']['coupon_click_url'] != '') {
                return ['status' => true, 'msg' => $res['data']['coupon_click_url']];
            } else {
                return ['status' => true, 'msg' => $res['data']['item_url']];
            }
        }
    }


    /**
     * @param $request_url 请求地址
     * @param $request_data 请求参数
     * @return bool|mixed|string 请求结果
     */
    public static function request_post($request_url, $request_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $request_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request_data);
        $res = curl_exec($ch);
//        var_dump($res);exit;
        curl_close($ch);
        $res = json_decode($res, true);
        return $res;
    }


    /**
     * @func 京东商品转链
     * @param $goods_id 商品id
     * @return |null
     */
    static public function jd_turn($user_id, $goods_id)
    {
        $materialId           = 'https://item.jd.com/' . $goods_id . '.html';
        $params               = [
            'v'           => '1.0',
            'method'      => 'jd.union.open.promotion.bysubunionid.get',//self::JD_APP['METHOD'];
            'app_key'     => '79ab36193d1acde1c7361d07c6e124b6',//self::JD_APP['KEY'];
            'sign_method' => 'md5',
            'format'      => 'json',
            'timestamp'   => date('Y-m-d H:i:s', time()),
        ];
        $data['materialId']   = $materialId;
        $data['siteId']       = 1780707606;
        $data['subUnionId']   = $user_id;
        $params['param_json'] = str_replace('\\', '', json_encode(['promotionCodeReq' => $data]));
        $secret               = '1167f168d96b48d1a21911361b78adc2';//self::JD_APP['SECRET'];
        $params['sign']       = (new CommonController())->sign($params, $secret);
        $url                  = 'https://router.jd.com/api' . '?' . http_build_query($params);
        $output               = self::request_get($url);
        $output               = json_decode($output, true);
        if (empty($output)) {
            return ['status' => false, 'msg' => '请求地址有问题,没有获取到数据'];
        } else {
            if (isset($output['jd_union_open_promotion_bysubunionid_get_response'])) {
                if (isset($output['jd_union_open_promotion_bysubunionid_get_response']['code']) && $output['jd_union_open_promotion_bysubunionid_get_response']['code'] == 0) {
                    $result = json_decode($output['jd_union_open_promotion_bysubunionid_get_response']['result'], true);
                    if ($result['code'] == 200) {
                        return ['status' => true, 'msg' => $result['data']['shortURL']];
                    }
                } else {
                    return ['status' => false, 'msg' => '请求成功，但没有数据'];
                }
            } else {
                return ['status' => false, 'msg' => $output['error_response']['zh_desc']];
            }
        }
    }


    /**
     * @param $url 请求地址
     * @return bool|string 请求结果
     */
    public static function request_get($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


    /**
     *  数据签名
     */
    public function sign($params, $secret)
    {
        ksort($params);
        $str = '';
        foreach ($params as $name => $value) {
            $str .= "{$name}{$value}";
        }
        return strtoupper(md5(implode('', [$secret, $str, $secret])));
    }


    /**
     * @func获取拼多多的转链
     */
    public static function pdd_turn($goods_id, $pid)
    {
        $xcx_params = [
            'goods_id_list'      => "[$goods_id]",
            'generate_short_url' => "true",
            'p_id'               => $pid,
            'generate_we_app'    => 'true',
            'type'               => 'pdd.ddk.goods.promotion.url.generate'//config('api.pin_duo_duo.product.promotion_url'),
        ];
        $app_params = [
            'goods_id_list'      => "[$goods_id]",
            'generate_short_url' => "true",
            'p_id'               => $pid,
            //'generate_we_app'=>'true',
            'type'               => 'pdd.ddk.goods.promotion.url.generate'//config('api.pin_duo_duo.product.promotion_url'),
        ];


        $params                    = array_merge($xcx_params, [
            'timestamp' => time(),
            'data_type' => 'JSON',
            'client_id' => '7660afbae5ae46afba6c3f4b6eae194b',
        ]);
        $pdd_secret                = '13c469653d505b6aa162083cfc268029bc8906f5';
        $params                    = array_merge($params, ['sign' => (new CommonController())->sign($params, $pdd_secret)]);
        $pdd_params['form_params'] = $params;
        $url                       = 'http://gw-api.pinduoduo.com/api/router';
        $response                  = self::request_post($url, http_build_query($params));
        if (isset($response['error_response'])) {
            return ['status' => false, 'msg' => $response['error_response']['error_msg']];
        } else {
            $data = $response['goods_promotion_url_generate_response']['goods_promotion_url_list'][0];
            //注释2.0的
//            $result = (new CommonController())->promotion($goods_id,$pid,$data);
//            return ['status'=>true,'short_url'=>$data['short_url'],'msg'=>$result['url']];

            return ['status' => true, 'msg' => $data];//拼多多的所有链接
        }
    }

    /**
     * @func 拼多多的所有链接
     * @param $goods_id
     * @param $pid
     * @param $data 拼多多返回回来的所有数据
     * @return array
     */
    public function promotion($goods_id, $pid, $data)
    {
        return [
            'url'           => str_replace(['{ID}', '{PID}'], [$goods_id, $pid], 'pinduoduo://com.xunmeng.pinduoduo/duo_coupon_landing.html?goods_id={ID}&pid={PID}&t=JDj7m0HqSXQbTTWKnb0jjHkWGN3zVjAa9Hs5ZUD0O0s='),
            'short_url'     => $data['mobile_short_url'],
            'view_view_url' => $data['we_app_web_view_short_url'],
            'app_view_url'  => $data['we_app_web_view_url'],
        ];
    }


    /**
     * @func 淘宝授权
     * @param $user_id 用户id
     */
    public static function taobao_authorizes($user_id)
    {
        $url   = 'https://oauth.taobao.com/authorize';
        $param = [
            'client_id'     => '25284833',//self::TAOBAO_APP['CLIENT_ID'],
            'response_type' => 'code',
            'redirect_uri'  => 'http://api.jiruanos.com/login/relationCallback',//'http://api.jiruanos.com/login/relationCallback',
            'view'          => 'wap',
            'state'         => $user_id,
        ];
        return $url = $url . '?' . http_build_query($param);
    }


    /**
     * 获取本地域名
     */
    public static function domain()
    {
        $url = '';
        if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
            $url = 'https://';
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
            $url = 'https://';
        } elseif (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
            $url = 'https://';
        } else {
            $url = 'http://';
        }
        $url = $url . $_SERVER['HTTP_HOST'];
        return $url;
    }


    /**
     *  足迹收藏
     */
    public static function footprints($params, $res)
    {
        $data['user_id']      = $params['user_id'];
        $data['product_id']   = $res['GoodsId'];
        $data['site']         = $res['Site'];
        $data['created_time'] = date('Y-m-d H:i:s', time());
        $data['updated_at']   = date('Y-m-d H:i:s', time());
        $footprints           = new Footprints();
        $footprints->footprint_save($data);
    }


    /**
     * 对象转数组
     */
    public static function transition_array($obj, $page = '')
    {
        $arr_str  = json_encode($obj);
        $arr_json = json_decode($arr_str, true);
        if (!empty($page)) {
            if ($arr_json['total_pages'] < $page) {
                $arr_json['items']   = [];
                $arr_json['current'] = $page;
                return $arr_json;
            }
        }
        return $arr_json;
    }


    /**
     *  收藏 我的足迹获取淘宝商品
     *
     */
    public function return_list($page, $cache, $haodanku, $jd, $pdd)
    {
        foreach ($page['items'] as $key => &$value) {
            $redis_key = "goods_detail_{$value['site']}_{$value['product_id']}";
            $res       = $cache->get_cache($redis_key);
            if (!$res) {
                if ($value['site'] == 'haodanku' || $value['site'] == 'elm' || $value['site'] == 'koubei') {
                    $res = $haodanku->goods_detail($value['product_id']);
                    if ($res == false) {
                        $res['Title']       = $value['goodsTitle'] = '已失效';
                        $res['ShopName']    = $res['ShortTitle'] = $res['PicLogo'] = $res['Couponurl'] = '';
                        $res['CouponMoney'] = $res['MonthSale'] = $res['CouponMoney'] = $res['EndPrice'] = $res['Commission'] = $res['Price'] = 0;
                    }
                }
                if ($value['site'] == 'jd') {
                    $res = $jd->goods_detail($value['product_id']);
                }
                if ($value['site'] == 'pdd') {
                    $res = $pdd->goods_detail($value['product_id']);
                }
                if ($value['site'] == 'vph') {
                    $res = $pdd->goods_detail($value['product_id']);
                }
                if (empty($res['Title'])) {
                    $res['Title']       = '已失效';
                    $res['ShopName']    = $res['ShortTitle'] = $res['PicLogo'] = $res['Couponurl'] = '';
                    $res['CouponMoney'] = $res['MonthSale'] = $res['CouponMoney'] = $res['EndPrice'] = $res['Commission'] = $res['Price'] = 0;
                }
            }
            $value['ShopType']    = isset($res['ShopType']) ? $res['ShopType'] : '';
            $value['goodsTitle']  = $res['Title'];
            $value['ShopName']    = $res['ShopName'];
            $value['ShortTitle']  = $res['ShortTitle'];
            $value['Price']       = $res['Price'];
            $value['PicLogo']     = $res['PicLogo'];
            $value['CouponMoney'] = $res['CouponMoney'];
            $value['MonthSale']   = $res['MonthSale'];
            $value['CouponMoney'] = $res['CouponMoney'];
            $value['EndPrice']    = $res['EndPrice'];
            $value['CouponUrl']   = $res['Couponurl'];
            $value['Commission']  = $res['Commission'];

            $cache->set_cache($redis_key, $res);
        }
        return $page;
    }


    /**
     * @param $path 路径
     * @param $referer_id 父级id
     */
    public static function invite($referer_id, $path)
    {     //父级id
        $user         = new User();
        $referer_user = $user->find_by_firstId($referer_id);
        if (!empty($referer_user)) {
            $referer_user['direct_vip'] = $referer_user['direct_vip'] + 1;      //父级直邀人数加1
            $referer_user['team_scale'] = $referer_user['indirect_vip'] + $referer_user['direct_vip'];
            $user->save_user($referer_user);
            if ($path) {
                $indirect_ids = explode(',', $path);
                foreach ($indirect_ids as $key => $value) {
                    $user1         = new User();
                    $indirect_user = $user->find_by_firstId($value);
                    if ($indirect_user) {
                        $indirect_user['indirect_vip'] = $indirect_user['indirect_vip'] + 1;    //path里面的人数加1
                        $indirect_user['team_scale']   = $indirect_user['direct_vip'] + $indirect_user['indirect_vip'];
                        $user1->save_user($indirect_user);
                    }
                }
            }
        }
    }


    /**
     * 分页
     */
    public static function paging($list, $count, $page_size, $page)
    {
        if (round($count / $page_size) == 0) {
            $total_page = 1;
        } else {
            $total_page = $count / $page_size;
        }
        $data['items']       = $list;
        $data['first']       = 1;
        $data['before']      = $page > 1 ? $page - 1 : $page;
        $data['current']     = $page;
        $data['last']        = $count > 0 ? (int)$total_page : 0;
        $data['next']        = (int)$total_page > $page + 1 ? $page + 1 : $page;
        $data['total_pages'] = $count > 0 ? (int)$total_page : 0;
        $data['total_items'] = $count;
        $data['limit']       = $page_size;
        return $data;
    }

    /**
     * 生成商品海报
     */
    public static function goods_poster($goods)
    {
        $share_img = $goods['PicLogo'];
        //计算原图长宽比例
        //新图尺寸
        //生成海报
        $font           = APP_PATH . 'public/static/simsun.ttf';   //保证字体文件目录正确
        $font_cu        = APP_PATH . 'public/static/songcu.ttf';   //保证字体文件目录正确
        $filepath       = APP_PATH . 'public/static/haibao/p.jpg';
        $posters_width  = 450;                   //画布宽度
        $posters_height = 700;
        $newimg         = imagecreatetruecolor($posters_width, $posters_height);
        $bg             = imagecolorallocate($newimg, 244, 244, 244);
        imagefill($newimg, 0, 0, $bg);
        //写分享图片
        $new_shareim = imagecreatefromstring(file_get_contents($share_img));
        imagecopy($newimg, $new_shareim, 0, 0, 0, 0, 450, 350);      //写入商品图片

        //-----------------------------------------------------------商品相关----------------------------------
        $filepath_goods = APP_PATH . 'public/static/haibao/goods_p.jpg';
        $posters_width  = 450;                   //画布宽度
        $posters_height = 220;
        $goods_newimg   = imagecreatetruecolor($posters_width, $posters_height);
        $goods_bg       = imagecolorallocate($goods_newimg, 255, 255, 255);
        imagefill($goods_newimg, 0, 0, $goods_bg);
        //商品标题
        $black = imagecolorallocate($goods_newimg, 0, 0, 0);
        $title = mb_substr($goods['Title'], 0, 11, 'utf-8') . '...';
        imagettftext($goods_newimg, 15, 0, 30, 40, $black, $font_cu, $title);
        $black = imagecolorallocate($goods_newimg, 176, 176, 176);
        imagettftext($goods_newimg, 12, 0, 30, 80, $black, $font, "{$goods['MonthSale']}人已购买");
        $black = imagecolorallocate($goods_newimg, 255, 0, 0);
        imagettftext($goods_newimg, 13, 0, 30, 120, $black, $font, '券后￥');
        imagettftext($goods_newimg, 20, 0, 100, 120, $black, $font_cu, "{$goods['EndPrice']}");
        $black = imagecolorallocate($goods_newimg, 176, 176, 176);
        imagettftext($goods_newimg, 10, 0, 185, 120, $black, $font, "原价{$goods['Price']}");
        imagettftext($goods_newimg, 12, 0, 180, 120, $black, $font, '----------');
        $share_img   = 'http://jzcloud.jiruan.ltd/font/juan.png';
        $new_shareim = imagecreatefromstring(file_get_contents($share_img));
        imagecopy($goods_newimg, $new_shareim, 30, 150, 0, 0, 99, 30);      //写入商品图片
        $black = imagecolorallocate($goods_newimg, 255, 255, 255);
        imagettftext($goods_newimg, 15, 0, 30, 172, $black, $font_cu, " 卷 {$goods['CouponMoney']}元");
        //写二维码
        require_once "phpqrcode.php";
        $errorCorrectionLevel = 'L';  //容错级别
        $matrixPointSize      = 4;      //生成图片大小
        //生成二维码图片
        ob_start();
        QRcode::png("{$goods['turn_url']}", false, $errorCorrectionLevel, $matrixPointSize, 2);
        $imgstr = 'data:image/png;base64,' . base64_encode(ob_get_contents());
        //$imgstr =base64_encode(ob_get_contents());
        ob_end_clean();
        if (strstr($imgstr, ",")) {
            $imgstr = explode(',', $imgstr);
            $imgstr = $imgstr[1];
        }
        $imageName     = APP_PATH . 'public/static/haibao/' . date("His", time()) . "_" . rand(1111, 9999) . '.jpg';
        $ostream_image = file_put_contents($imageName, base64_decode($imgstr));//返回的是字节数
        if ($ostream_image) {
            //$er_shareim = imagecreatefromstring(file_get_contents('http://jzcloud.jiruan.ltd/img/ad/tb.png'));
            $er_shareim = imagecreatefromstring(file_get_contents($imageName));
            imagecopy($goods_newimg, $er_shareim, 260, 5, 0, 0, 150, 150);
            $gray = imagecolorallocate($goods_newimg, 136, 136, 136);
            @unlink($imageName);
        }
        $black = imagecolorallocate($goods_newimg, 144, 144, 144);
        imagettftext($goods_newimg, 10, 0, 285, 175, $black, $font, '长按二维码领劵');

        //海报生成保存
        imagejpeg($goods_newimg, $filepath_goods);
        ImageDestroy($goods_newimg);
        $new_shareim = imagecreatefromstring(file_get_contents($filepath_goods));
        imagecopy($newimg, $new_shareim, 10, 370, 0, 0, 430, 200);      //写入商品图片
        $changan     = APP_PATH . "public/static/haibao/changan.jpg";//http://jzcloud.jiruan.ltd/font/changan.jpg
        $new_shareim = imagecreatefromstring(file_get_contents($changan));
        imagecopy($newimg, $new_shareim, 0, 560, 0, 0, 450, 133);      //写入商品图片
        //海报生成保存
        imagejpeg($newimg, $filepath);
        ImageDestroy($newimg);
        $base64_file = '';
        if (file_exists($filepath)) {
            $mime_type   = mime_content_type($filepath);
            $base64_data = base64_encode(file_get_contents($filepath));
            //$base64_file = 'data:'.$mime_type.';base64,'.$base64_data;
            $base64_file = $base64_data;
        }
        return $base64_file;
    }


    /**
     * 获取用户的ip
     */
    public static function get_real_ip()
    {
        $ip = false;
        if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) {
                array_unshift($ips, $ip);
                $ip = FALSE;
            }
            for ($i = 0; $i < count($ips); $i++) {
                if (!eregi("^(10|172\.16|192\.168)\.", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }


    /**
     * 根据ASICC字符对数组进行排序
     * @param array $params
     * @return bool|string
     */
    public static function asc_sort($params = array())
    {
        if (!empty($params)) {
            $p = ksort($params);
            if ($p) {
                $str = '';
                foreach ($params as $k => $val) {
                    $str .= $k . '=' . $val . '&';
                }
                $strs = rtrim($str, '&');
                return $strs;
            }
        }
        return false;
    }

    /**
     * 判断日期是否是合法的
     */
    public static function is_datatime($data)
    {
        $date = strtotime($data);
        if ($data == (date("Y-m-d", $date)) || $data == (date("Y-m-j", $date)) || $data == (date("Y-n-d", $date)) || $data == (date("Y-n-j", $date)))
            return true;
        else
            return false;
    }


    /**
     * 获取卡密口令
     */
    public static function kouling()
    {
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0, 25)]
            . strtoupper(dechex(date('m')))
            . date('d')
            . substr(time(), -5)
            . substr(microtime(), 2, 5)
            . sprintf('%02d', rand(0, 99));
        for (
            $a = md5($rand, true),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
            $d = '',
            $f = 0;
            $f < 6;
            $g = ord($a[$f]),
            $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
            $f++
        ) ;
        return $d;
    }

    /**
     * 计算两个时间之差
     * @param $time
     * @return string
     */
    public static function format_date($date)
    {
        $time = strtotime($date);
        $t    = time() - $time;
        $f    = array(
            '31536000' => '年',
            '2592000'  => '个月',
            '604800'   => '星期',
            '86400'    => '天',
            '3600'     => '小时',
            '60'       => '分钟',
            '1'        => '秒'
        );
        foreach ($f as $k => $v) {
            if (0 != $c = floor($t / (int)$k)) {
                return $c . $v . '前';
            }
        }
    }

    /**
     * h5设置签名
     */
    public static function h5mcrypt($user_id, $params = [])
    {
        $obj               = new AESH5Mcrypt();
        $data['h5_domain'] = 'http://h5.tes.jiruan.ltd/';
        $data['user_id']   = $user_id;
        $data['times']     = date('Y-m-d H:i:s') . '_' . rand(1, 2000);
        $data['h5params']  = $params;
        $str               = $obj->encrypt(json_encode($data));
        return $str;
    }


    //获取用户名称
    public static function get_user_nickname($phone, $nickname, $wx_nickname)
    {
        $name = '匿名';
        if ($nickname || $wx_nickname || $phone) {             //获取当前我的昵称 判断 以前的nickname 后面添加了一个wx_nickname 如果没有的话就取电话号码
            $name = $nickname ? $nickname : $wx_nickname;
            if (empty($name)) {
                $referer_phone = substr_replace($phone, '****', 3, 4);
                $name          = $referer_phone;
            }
        }
        return $name;
    }


    //对小数不进行四舍五入
    public static function number_randtwo($number,$num=3)
    {
        return substr(sprintf("%.{$num}f", $number), 0, -1);
    }


    //推送
    public static function tuisong($title,$detail,$router_arr=[])
    {
        $route  = [
            'type'   => isset($router_arr['type']) ? $router_arr['type'] : 1,
            'path'   => isset($router_arr['app_path']) ? $router_arr['app_path'] : 'AwakeMsg',
            'title'  => $title,
            'url'    => isset($router_arr['url']) ? $router_arr['url'] : '',
            'data'   => isset($router_arr['app_data']) ? $router_arr['app_data'] : '',
            'notice' => null,
        ];
        $jpush = new Jpush();
        $jpush->pushmsg_all([], $title, $detail, $route);
    }

    public static function ReservedCommission($commission, $site)
    {
        $appConfig = new AppConfig();

        switch ($site) {
            case 'haodanku':
                $config = $appConfig->find_first_type('taobao_commission');
                if ($config->value > 0) {
                    $commission = self::number_randtwo($commission * (100 - $config->value) / 100);
                }
                break;
            case 'jd':
                $config = $appConfig->find_first_type('jd_commission');
                if ($config->value > 0) {
                    $commission = self::number_randtwo($commission * (100 - $config->value) / 100);
                }
                break;
            case 'pdd':
                $config = $appConfig->find_first_type('pdd_commission');
                if ($config->value > 0) {
                    $commission = self::number_randtwo($commission * (100 - $config->value) / 100);
                }
                break;
        }
        return $commission;
    }


}
